package com.budwk.app.waterquality.services.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.utils.PoiUtil;
import com.budwk.app.waterquality.config.AppException;
import com.budwk.app.waterquality.config.constant.FileConstant;
import com.budwk.app.waterquality.models.FileInfo;
import com.budwk.app.waterquality.models.MonthlyReport;
import com.budwk.app.waterquality.models.WaterQualityIndicator;
import com.budwk.app.waterquality.services.FileInfoService;
import com.budwk.app.waterquality.services.MonthlyReportService;
import com.budwk.app.waterquality.services.WaterQualityIndicatorService;
import com.budwk.app.waterquality.vo.ParamProblemVo;
import com.budwk.app.waterquality.vo.TemplateConfigQueryVo;
import com.budwk.app.waterquality.vo.WaterQualityVo;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.database.service.BaseServiceImpl;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

@IocBean(args = {"refer:dao"})
public class MonthlyReportServiceImpl extends BaseServiceImpl<MonthlyReport> implements MonthlyReportService {
    public MonthlyReportServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private WaterQualityIndicatorService waterQualityIndicatorService;
    @Inject
    private FileInfoService fileInfoService;

    @Override
    public List<WaterQualityIndicator> getById(String id) {
        MonthlyReport report = this.fetch(id);
        if (report == null) {
            throw new AppException("数据不存在！");
        }
        List<WaterQualityIndicator> list = waterQualityIndicatorService.query(Cnd.where(WaterQualityIndicator::getTemplateId, "=", report.getTemplateId()));
        return list;
    }

    @Override
    public Pagination listByPage(TemplateConfigQueryVo bean) {
        Cnd cnd = Cnd.NEW();
        SqlExpressionGroup where = cnd.where();
        Pagination pagination = this.listPage(bean.getPageNo(), bean.getPageSize(), cnd);
        return pagination;
    }

    @Override
    public String downData(String id, HttpServletResponse response) {
        MonthlyReport report = this.fetch(id);
        if (report == null) {
            throw new AppException("数据不存在！");
        }
        List<WaterQualityIndicator> list = waterQualityIndicatorService.query(Cnd.where(WaterQualityIndicator::getTemplateId, "=", report.getTemplateId()));
        if (CollectionUtil.isEmpty(list)) {
            throw new AppException("没有数据导出！");
        }
        List<String> titles = buildTitle(list);
        SXSSFWorkbook book = new SXSSFWorkbook();// 没有行数限制 不占内存（通用）
        book.setCompressTempFiles(true);  //开启压缩配置项
        SXSSFSheet sheet = book.createSheet();
        SXSSFRow row = sheet.createRow(0);
        for (int i = 0; i < titles.size(); i++) {
            SXSSFCell cell = row.createCell(i);
            cell.setCellValue(titles.get(i));
        }
        int rowIndex = 1;
        for (WaterQualityIndicator w : list) {
            SXSSFRow row1 = sheet.createRow(rowIndex);
            List<String> content = buildContent(String.valueOf(rowIndex), report, w);
            for (int i = 0; i < content.size(); i++) {
                SXSSFCell cell = row1.createCell(i);
                cell.setCellValue(content.get(i));
            }
            rowIndex ++;
        }
        String downFileUrl = PoiUtil.getDownFileUrl(System.currentTimeMillis() + ".xlsx", book, response);
        return downFileUrl;
    }

    private List<String> buildContent(String index, MonthlyReport report, WaterQualityIndicator w) {
        WaterQualityVo waterQualityVo = JSONObject.parseObject(w.getWaterQualityData(), WaterQualityVo.class);
        List<String> conetents = new java.util.ArrayList<>(List.of(index, report.getFileName(), waterQualityVo.getSPT()));
        conetents.addAll(waterQualityVo.getWaterParam().stream().map(ParamProblemVo::getValue).collect(Collectors.toList()));
        conetents.add(w.getRemark());
        return conetents;
    }
    private List<String> buildTitle(List<WaterQualityIndicator> list) {
        List<String> titles = new java.util.ArrayList<>(List.of("序号", "名称", "采样时间"));
        WaterQualityIndicator w = list.get(0);
        WaterQualityVo waterQualityVo = JSONObject.parseObject(w.getWaterQualityData(), WaterQualityVo.class);
        titles.addAll(waterQualityVo.getWaterParam().stream().map(ParamProblemVo::getName).collect(Collectors.toList()));
        titles.add("备注");
        return titles;
    }
}
